package cn.dg.manager.order.service.impl;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.util.StringUtils;

import cn.dg.manager.base.util.DateUtil;
import cn.dg.manager.common.entity.GoodsComboboxBean;
import cn.dg.manager.common.entity.PageEntity;
import cn.dg.manager.order.dao.OrderDetailDao;
import cn.dg.manager.order.dao.OrderInfoDao;
import cn.dg.manager.order.entity.OrderDetailResultBean;
import cn.dg.manager.order.entity.OrderDetailVO;
import cn.dg.manager.order.entity.OrderEditPageBean;
import cn.dg.manager.order.entity.OrderInfoResultBean;
import cn.dg.manager.order.entity.OrderInfoVO;
import cn.dg.manager.order.entity.OrderPageParam;
import cn.dg.manager.order.service.OrderService;
import cn.dg.manager.user.address.dao.UserAddressDao;
import cn.dg.manager.user.address.entity.UserAddressInfoVO;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service("orderService")
public class OrderServiceImpl implements OrderService {

	public static String[] ORDER_INFO_HEADER = {"订单名称","订单总金额","收货人","手机号","收货地址","订单状态","订单时间"};
	public static String[] ORDER_DETAIL_HEADER = {"商品分类","商品名称","商品单价","购买商品数量","商品购买总价"};
	public static int ORDER_INFO_CELL_START_INDEX = 1;
	public static String UTF_8 = "UTF-8";
	
	@Autowired
	OrderInfoDao orderInfoDao;
	
	@Autowired
	OrderDetailDao orderDetailDao;
	
	@Autowired
	UserAddressDao userAddressDao;
	
	public PageEntity<OrderInfoResultBean> getOrderListPage(Map<String, Object> params) {
        PageEntity<OrderInfoResultBean> list = orderInfoDao.findOrderListPagePage(params);
        return list;
	}

	/**
	 * 生成订单信息
	 */
	@Transactional(rollbackFor=Exception.class)
	public long insertOrderInfo(OrderPageParam bean) {
		OrderInfoVO orderInfoVO = getOrderInfoCopyValue(bean);
		orderInfoDao.insertOrderInfo(orderInfoVO);
		int orderDetailCnt = insertOrderDetailInfo(orderInfoVO.getOrderId(), bean.getOrderDetailJsonObject());
		return orderDetailCnt;
	}
	
	/**
	 * 更新订单数据
	 */
	@Transactional(rollbackFor=Exception.class)
	public long updateOrderInfo(OrderPageParam bean) {
		OrderInfoVO orderInfoVO = getOrderInfoCopyValue(bean);
		orderInfoDao.updateOrderInfo(orderInfoVO);
		int updateDetailCnt = updateOrderDetailInfo(orderInfoVO.getOrderId(), bean.getOrderDetailJsonObject());
		return updateDetailCnt;
	}

	/**
	 * 准备订单基本信息
	 * @param bean
	 * @return
	 */
	private OrderInfoVO getOrderInfoCopyValue(OrderPageParam bean) {
		// 地址ID设定
		bean.setAddressId(saveAddressInfo(bean));
		OrderInfoVO orderInfoVO = new OrderInfoVO();
		orderInfoVO.setOrderId(bean.getOrderId());
		orderInfoVO.setOrderName(bean.getOrderName());
		orderInfoVO.setAddressId(bean.getAddressId());
		orderInfoVO.setTotalCnt(bean.getTotalCnt());
		orderInfoVO.setFreight(bean.getFreight());
		orderInfoVO.setTotalPrice(bean.getTotalPrice());
		orderInfoVO.setTotalPriceJp(bean.getTotalPriceJp());
		orderInfoVO.setDelFlg(0);
		return orderInfoVO;
	}

	/**
	 * 更新订单详细
	 * 
	 * @param orderId
	 * @param orderDetailJsonObject
	 * @return
	 */
	private int updateOrderDetailInfo(Integer orderId, Object orderDetailJsonObject) {
		int rslt = 0;
		// 删除全部订单详情
		rslt += orderDetailDao.delOrderDetailInfoByOrderIDList(Arrays.asList(orderId.toString()));
		// 全新插入
		rslt += insertOrderDetailInfo(orderId, orderDetailJsonObject);
		return rslt;
	}

	/**
	 * 
	 * @param orderId
	 * @param orderDetailJsonObject
	 * @return
	 */
	private int insertOrderDetailInfo(Integer orderId, Object orderDetailJsonObject) {
		int insertCnt = 0;
		JSONArray orderDetailJson = JSONArray.fromObject(orderDetailJsonObject);
		if(orderDetailJson != null && orderDetailJson.size() > 0) {
			List<OrderDetailVO> orderDetailVOList = new ArrayList<OrderDetailVO>(orderDetailJson.size());
			for (int i = 0; i < orderDetailJson.size(); i++) {
				OrderDetailVO orderDetailVO = (OrderDetailVO)JSONObject.toBean(
						orderDetailJson.getJSONObject(i), OrderDetailVO.class);
				orderDetailVO.setOrderId(orderId);
				orderDetailVO.setSort(i + 1);
				orderDetailVOList.add(orderDetailVO);
			}
			insertCnt = orderDetailDao.insertOrderDetailList(orderDetailVOList);
		}
		return insertCnt;
	}

	/**
	 * 收货地址设定
	 * @param bean
	 * @return
	 */
	private Integer saveAddressInfo(OrderPageParam bean) {
		Integer addressId = 0;
		if (StringUtils.isEmpty(bean.getUserName())) {
			return addressId;
		}
		
		UserAddressInfoVO addressVO = new UserAddressInfoVO();
		addressVO.setUserName(bean.getUserName());
		addressVO.setPostCode(bean.getPostCode());
		addressVO.setTelPhone(bean.getTelPhone());
		addressVO.setAddress(bean.getAddress());
		// 新增
		if(bean.getAddressId() == null || bean.getAddressId() == 0) {
			long rslt = userAddressDao.insertUserAddressInfo(addressVO);
			if (rslt > 0) {
				addressId = addressVO.getAddressId();
			}
		} else {
			Map<String, Object> conds = new HashMap<String, Object>();
			conds.put("userName", bean.getUserName());
			conds.put("postCode", bean.getPostCode());
			conds.put("telPhone", bean.getTelPhone());
			conds.put("address", bean.getAddress());
			long rslt = userAddressDao.findUserAddressByCond(conds);
			if (rslt <= 0 ) {
				long insertRslt = userAddressDao.insertUserAddressInfo(addressVO);
				if (insertRslt > 0) {
					addressId = addressVO.getAddressId();
				}
			} else {
				addressId = bean.getAddressId();
			}
		}
		return addressId;
	}

	/**
	 * 删除订单信息
	 */
	@Transactional(rollbackFor=Exception.class)
	public long deleteOrderInfo(List<String> orderIDList) {
		long rslt = 0;
		rslt = orderDetailDao.delOrderDetailInfoByOrderIDList(orderIDList);
		rslt += orderInfoDao.deleteOrderInfoByIds(orderIDList);
		return rslt;
	}

	public List<OrderDetailResultBean> getOrderDetailInfo(Map<String, Object> params) {
		return orderDetailDao.getOrderDetailInfo(params);
	}

	public List<GoodsComboboxBean> getGoodsComboboxList() {
		return orderDetailDao.getGoodsComboboxList();
	}

	/**
	 * 获取编辑的订单数据
	 */
	public OrderEditPageBean getOrderInfo(String orderId) {
		OrderEditPageBean result = orderInfoDao.getOrderInfo(orderId);
		List<OrderDetailVO> itemList = orderDetailDao.getOrderDetailEditInfo(orderId);
		result.setItem(itemList);
		return result;
	}

	/**
	 * 根据订单号导出订单文件
	 */
	public void exportExcelFile(String orderId, HttpServletResponse response) {
	    response.setCharacterEncoding(UTF_8);  
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");  
        response.setHeader("Pragma", "no-cache");  
        response.setHeader("Cache-Control", "no-cache");  
        response.setDateHeader("Expires", 0);  
        
		OrderEditPageBean orderInfo = orderInfoDao.getOrderInfo(orderId);
		Map<String, Object> params = new HashMap<String, Object>(1);
		params.put("orderId", orderId);
		List<OrderDetailResultBean> orderDetailInfo = orderDetailDao.getOrderDetailInfo(params);
		
		String fileName = orderInfo.getOrderName().concat("_") + DateUtil.getSdfTimes() + ".xlsx";
		try {
			fileName = new String(fileName.getBytes(UTF_8), "ISO_8859_1");
		} catch (UnsupportedEncodingException e1) {
			fileName = DateUtil.getSdfTimes() + ".xlsx";
		}

		response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);  
		
		XSSFWorkbook workbook = new XSSFWorkbook();
		XSSFSheet sheet = workbook.createSheet(orderInfo.getOrderName());
		
		int createExcelRowCnt = 0;
		XSSFCellStyle  cellStyle = workbook.createCellStyle();
		cellStyle.setBorderLeft(BorderStyle.THIN);
		cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);
        cellStyle.setBorderTop(BorderStyle.THIN);

		XSSFCell cellHeader  = null;
		XSSFRow row  = null;
		
		int i = 0;
		// 订单名称
		row  = sheet.createRow(createExcelRowCnt);
		cellHeader = row.createCell(ORDER_INFO_CELL_START_INDEX);
		cellHeader.setCellValue(ORDER_INFO_HEADER[i]);
		cellHeader.setCellStyle(cellStyle);
		cellHeader = row.createCell(ORDER_INFO_CELL_START_INDEX + 1);
		cellHeader.setCellValue(orderInfo.getOrderName());
		cellHeader.setCellStyle(cellStyle);
		i++;
		createExcelRowCnt++;
		
		// 订单金额
		row  = sheet.createRow(createExcelRowCnt);
		cellHeader = row.createCell(ORDER_INFO_CELL_START_INDEX);
		cellHeader.setCellValue(ORDER_INFO_HEADER[i]);
		cellHeader.setCellStyle(cellStyle);
		cellHeader = row.createCell(ORDER_INFO_CELL_START_INDEX + 1);
		cellHeader.setCellValue(orderInfo.getTotalPrice());
		cellHeader.setCellStyle(cellStyle);
		i++;
		createExcelRowCnt++;
		
		// 收货人
		row  = sheet.createRow(createExcelRowCnt);
		cellHeader = row.createCell(ORDER_INFO_CELL_START_INDEX);
		cellHeader.setCellValue(ORDER_INFO_HEADER[i]);
		cellHeader.setCellStyle(cellStyle);
		cellHeader = row.createCell(ORDER_INFO_CELL_START_INDEX + 1);
		cellHeader.setCellValue(orderInfo.getUserName());
		cellHeader.setCellStyle(cellStyle);
		i++;
		createExcelRowCnt++;
		
		// 手机号
		row  = sheet.createRow(createExcelRowCnt);
		cellHeader = row.createCell(ORDER_INFO_CELL_START_INDEX);
		cellHeader.setCellValue(ORDER_INFO_HEADER[i]);
		cellHeader.setCellStyle(cellStyle);
		cellHeader = row.createCell(ORDER_INFO_CELL_START_INDEX + 1);
		cellHeader.setCellValue(orderInfo.getTelPhone());
		cellHeader.setCellStyle(cellStyle);
		i++;
		createExcelRowCnt++;
		
		// 收货地址
		row  = sheet.createRow(createExcelRowCnt);
		cellHeader = row.createCell(ORDER_INFO_CELL_START_INDEX);
		cellHeader.setCellValue(ORDER_INFO_HEADER[i]);
		cellHeader.setCellStyle(cellStyle);
		cellHeader = row.createCell(ORDER_INFO_CELL_START_INDEX + 1);
		cellHeader.setCellValue(orderInfo.getAddress());
		cellHeader.setCellStyle(cellStyle);
		i++;
		createExcelRowCnt++;
		
		// 订单状态
		row  = sheet.createRow(createExcelRowCnt);
		cellHeader = row.createCell(ORDER_INFO_CELL_START_INDEX);
		cellHeader.setCellValue(ORDER_INFO_HEADER[i]);
		cellHeader.setCellStyle(cellStyle);
		cellHeader = row.createCell(ORDER_INFO_CELL_START_INDEX + 1);
		cellHeader.setCellValue(getOrderState(orderInfo.getOrderState()));
		cellHeader.setCellStyle(cellStyle);
		i++;
		createExcelRowCnt++;
		
		// 订单状态
		row  = sheet.createRow(createExcelRowCnt);
		cellHeader = row.createCell(ORDER_INFO_CELL_START_INDEX);
		cellHeader.setCellValue(ORDER_INFO_HEADER[i]);
		cellHeader.setCellStyle(cellStyle);
		cellHeader = row.createCell(ORDER_INFO_CELL_START_INDEX + 1);
		cellHeader.setCellValue(orderInfo.getUpdateTime());
		cellHeader.setCellStyle(cellStyle);
		i++;
		createExcelRowCnt++;
		
		row  = sheet.createRow(++createExcelRowCnt);
		for (int j = 0; j < ORDER_DETAIL_HEADER.length; j++) {
			cellHeader = row.createCell(j + ORDER_INFO_CELL_START_INDEX + 2);
			cellHeader.setCellValue(ORDER_DETAIL_HEADER[j]);
			cellHeader.setCellStyle(cellStyle);
		}
		createExcelRowCnt++;
		
		for (OrderDetailResultBean bean : orderDetailInfo) {
			int orderDetailCellIndex = ORDER_INFO_CELL_START_INDEX + 2;
			row  = sheet.createRow(createExcelRowCnt++);
			
			// 商品分类
			cellHeader = row.createCell(orderDetailCellIndex);
			cellHeader.setCellValue(bean.getTypeName());
			cellHeader.setCellStyle(cellStyle);
			orderDetailCellIndex++;
			
			// 商品名称
			cellHeader = row.createCell(orderDetailCellIndex);
			cellHeader.setCellValue(bean.getGoodName());
			cellHeader.setCellStyle(cellStyle);
			orderDetailCellIndex++;
			
			// 商品单价
			cellHeader = row.createCell(orderDetailCellIndex);
			cellHeader.setCellValue(bean.getPrice());
			cellHeader.setCellStyle(cellStyle);
			orderDetailCellIndex++;
			
			// 购买商品数量
			cellHeader = row.createCell(orderDetailCellIndex);
			cellHeader.setCellValue(bean.getQuantity());
			cellHeader.setCellStyle(cellStyle);
			orderDetailCellIndex++;
			
			// 商品购买总价
			cellHeader = row.createCell(orderDetailCellIndex);
			cellHeader.setCellValue(bean.getTotalPrice());
			cellHeader.setCellStyle(cellStyle);
			orderDetailCellIndex++;
		}
		
		OutputStream output = null;
		BufferedOutputStream bufferedOutPut = null;
		try {
			output = response.getOutputStream();
			bufferedOutPut = new BufferedOutputStream(output);
			bufferedOutPut.flush();
			workbook.write(bufferedOutPut);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(bufferedOutPut);
			IOUtils.closeQuietly(output);
			IOUtils.closeQuietly(workbook);
		}
	}

	/**
	 * 获取订单状态
	 * @param orderState
	 * @return
	 */
	private String getOrderState(String orderState) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("0", "待支付");
		map.put("1", "已支付");
		map.put("2", "已取消");
		map.put("3", "已删除");
		
		return map.get(orderState);
	}
}
